package me.stone.stanimeclient.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import me.stone.stanimeclient.core.common.extensions.launchAndRepeatWithLifecycle
import me.stone.stanimeclient.util.autoCleared
import timber.log.Timber
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

interface INavigationHost {
    fun getToolbar(): Toolbar?
}

interface INavigationDestination {
    fun inflateToolbar(toolbar: Toolbar) {}
}

abstract class AbsViewBindingFragment<V: ViewBinding>: Fragment(), INavigationDestination {

    protected open var binding by autoCleared<V>()

    protected var navigationHost: INavigationHost? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = buildViewBinding(inflater, container)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        navigationHost?.getToolbar()?.let {
            inflateToolbar(it)
        }
    }

    abstract fun buildViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): V

    protected fun bindDataBinding(block: V.() -> Unit) {
        launchAndRepeatWithLifecycle {
            block.invoke(binding)
            (binding as? ViewDataBinding)?.run {
                lifecycleOwner = viewLifecycleOwner
                executePendingBindings()
            }
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is INavigationHost) {
            navigationHost = context
        } else {
            Timber.d("context not found navigation host: $context")
        }
    }

    override fun onDetach() {
        super.onDetach()
        navigationHost = null
    }

}